<?php

try {
    session_start();
    if (isset($_SESSION['name'])) {
        $name1 = $_SESSION['name'];
    } else {
        throw new Exception('未登录不允许操作');
    }
require_once 'img.inc.php';
    $root = $_SERVER['DOCUMENT_ROOT']; //绝对路径
    $path = $root . '/upload/';
    $time = time();
    $path .= date('y/m/d/', $time);
    var_dump($path);
    if (!file_exists($path) && !mkdir($path, 0777, true)) {
        throw new Exception('创建文件夹失败');
    }
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    $allow = array('jpg', 'jpeg', 'gif', 'png');
    if (!in_array($ext, $allow)) {
        throw new Exception('不允许的图像格式');
    }
    if ($_FILES['file']['size'] > 100 * 1024) {
        throw new Exception('图像太大，请选择较小的文件上传');
    }
    if ($_FILES['file']['size'] == 0) {
        throw new Exception('请选择文件上传');
    }
    $filename = $_FILES['file']['tmp_name'];

    $desname = md5(time() . $filename . mt_rand(1, 99999));
    $destination = $path . $desname . '.' . $ext;
    if (move_uploaded_file($filename, $destination)) {
//    echo '上传成功';
    } else {
        throw new Exception('移动文件失败');
    };
    $desname = suofang($destination, 50, 50);
    if (!$desname) {
        throw new Exception('缩放图像失败');
    }
    $finalname = str_replace($root, '', $desname);
    define('HOST', 'localhost');
    define('USER', 'mes');
    define('PASSWORD', '111111');
    define('DATABASE', 'mes');
    $conn = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
    if (!$conn) {
        throw new Exception('数据库连接失败');
    }
//    $sql = "select head from user_info where name='$name1'";
    $sql = "update user_info set head='$finalname' where name='$name1'";

    $res = mysqli_query($conn, $sql);                //执行sql命令
    $row = mysqli_fetch_assoc($res);
    $head = $row['head'];
    $oldsrc = $root . $row['head'];
    $oldsrc0 = str_replace('_50x50', '', $oldsrc);
         //准备sql语句
     var_dump($sql);
    if (mysqli_affected_rows($conn) != 1) {
        throw new Exception('头像更新失败');
    } else {
        if ($head) {
            unlink($oldsrc);
            unlink($oldsrc0);
        }
        echo '<script>alert("头像更新成功！");window.location="liuyan0.php"</script>';
    }
} catch (Exception $exc) {
    echo $exc->getMessage();
}
